package com.newhero.product.module.sys.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.newhero.product.common.controller.BaseController;
import com.newhero.product.common.mybatis.mapper.EntityWrapper;
import com.newhero.product.common.mybatis.plugins.Page;
import com.newhero.product.common.shiro.ShiroUser;
import com.newhero.product.common.util.BeanUtils;
import com.newhero.product.common.util.StringUtils;
import com.newhero.product.common.vo.ZTreeModel;
import com.newhero.product.module.sys.model.App;
import com.newhero.product.module.sys.model.Role;
import com.newhero.product.module.sys.model.User;
import com.newhero.product.module.sys.model.vo.RoleVo;
import com.newhero.product.module.sys.model.vo.UserVo;
import com.newhero.product.module.sys.service.IAppService;
import com.newhero.product.module.sys.service.IRoleService;
import com.newhero.product.module.sys.service.IUserService;

/**
 * @ClassName: RoleController 
 * @Description: 角色管理控制类 
 * @author Caolj 648198687@qq.com 
 * @date 2017-3-27 上午9:13:04
 */
@Controller
@RequestMapping("/admin")
public class RoleController extends BaseController {

	@Autowired 
	private IRoleService roleServiceImpl;
	@Autowired
	private IUserService userServiceImpl;
	@Autowired
	private IAppService appServiceImpl;
	@Autowired
	private IRoleService userRoleServiceImpl;

	@RequiresPermissions("/admin/role") 
	@RequestMapping(value = "/role", method = { RequestMethod.GET, RequestMethod.POST })
	public String role(
			@RequestParam(value = "page", defaultValue = "1", required = true) int page,// 页号
			@RequestParam(value = "rows", defaultValue = "" + _ROWS_PER_PAGE, required = true) int rows,// 每页显示的记录条数
			@RequestParam(value = "roleName", defaultValue = "", required = false) String roleName,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		Page<Role> p = new Page<Role>();
		p.setCurrent(page);
		p.setSize(rows);
		p.setOrderByField("roleOrder");
		EntityWrapper<Role> entityWrapper = new EntityWrapper<Role>();
		if(StringUtils.isNotBlank(roleName)){
			entityWrapper.like("roleName", roleName);
		}
		p = roleServiceImpl.selectPage(p,entityWrapper);
		model.addAttribute("data", p);
		model.addAttribute("roleName", roleName);
		return "sys/role/role";
	}

	@RequestMapping(value = "/roleForm", method = RequestMethod.GET)
	public String roleForm(String id, HttpServletRequest request) {
		if (id != null && !"".equals(id)) {
			request.setAttribute("roleID", id);
			request.setAttribute("formData", roleServiceImpl.selectById(id));
		} else {
			request.setAttribute("roleID", "");
		}
		return "sys/role/roleForm";
	}

	@RequestMapping(value = "/roleSave", method = RequestMethod.POST)
	public String roleSave(String roleID, Role role, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		try {
			if (!StringUtils.isBlank(roleID)) {
				Role sr = roleServiceImpl.selectById(roleID);
				BeanUtils.copy(role, sr);
				model.addAttribute("flag", "数据修改成功！");
				roleServiceImpl.updateById(sr);
			} else {
				model.addAttribute("flag", "数据添加成功！");
				roleServiceImpl.insert(role);
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return role(1, _ROWS_PER_PAGE, "", request, response, model);
	}

	@RequestMapping(value = "/roleEdit", method = RequestMethod.POST)
	@ResponseBody
	public Role roleEdit(@RequestParam(value = "id", required = true) String userID,
			HttpServletRequest request, HttpServletResponse response) {
		Role role = roleServiceImpl.selectById(userID);
		return role;
	}

	@RequestMapping(value = "/roleDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public String roleDelete(@RequestParam(value = "ids", required = true) String ids,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String[] idArr = ids.split(",");
		roleServiceImpl.deleteBatchIds(Arrays.asList(idArr));
		model.addAttribute("flag", "数据删除成功！");
		return role(1, _ROWS_PER_PAGE, "", request, response, model);
	}
	@RequestMapping(value = "/grantUser2")
	public String grantUser2(
			@RequestParam(value = "roleId", required = true) String roleId,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		model.addAttribute("roleId", roleId);
		return "sys/role/grantUser2";
	}

	@RequestMapping(value = "/grantUser")
	public String grantUser(
			@RequestParam(value = "roleId", required = true) String roleId,
			@RequestParam(value = "organID", defaultValue = "", required = true) String organID,
			@RequestParam(value = "page", defaultValue = "1", required = true) int page,// 页号
			@RequestParam(value = "rows", defaultValue = "" + _ROWS_PER_PAGE, required = true) int rows,// 每页显示的记录条数
			@RequestParam(value = "userLoginName", defaultValue = "", required = false) String userLoginName,
			@RequestParam(value = "userName", defaultValue = "", required = false) String userName,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		
		Page<UserVo> dataPage = new Page<UserVo>();
		dataPage.setCurrent(page);
		dataPage.setSize(rows);
		dataPage.setOrderByField("userOrder");
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		if (StringUtils.isNotBlank(roleId)) {
			params.put("roleID", roleId);
		}
		if (StringUtils.isNotBlank(organID)) {
			params.put("organID", organID);
		}
		if (StringUtils.isNotBlank(userLoginName)) {
			params.put("userLoginName", userLoginName);
		}
		
		dataPage.setRecords(userServiceImpl.selectUserListPage(dataPage, params));
		
		model.addAttribute("data", dataPage);
		model.addAttribute("roleId", roleId);
		Role role = roleServiceImpl.selectById(roleId);
		model.addAttribute("roleName", role.getRoleName());
		model.addAttribute("userLoginName", userLoginName);

		return "sys/role/grantUser";
	}

	@ResponseBody
	@RequestMapping(value = "/roleUserJSave")
	public Object roleUserJSave(@RequestParam(value = "roleId", required = true) String roleId,
			@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "type", required = true) String type, HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		if ("1".equals(type)) {
			roleServiceImpl.addUserRoleData(userId, roleId);
		} else {
			roleServiceImpl.removeUserRoleData(userId, roleId);
		}
		return renderSuccess("设置成功！");
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/roleAppJSave")
	public Object roleAppJSave(@RequestParam(value = "roleId", required = true) String roleId,
			@RequestParam(value = "appID", required = true) String appID,
			@RequestParam(value = "type", required = true) String type,
			HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		
		if ("1".equals(type)) {//说明要加权限
			roleServiceImpl.addRoleAppData(roleId, appID);
		} else {
			roleServiceImpl.removeRoleAppData(roleId, appID);
		}
		return renderSuccess("设置成功！");
	}

	@RequestMapping(value = "/grantApp")
	public String grantApp(@RequestParam(value = "roleId", required = true) String roleId,
			HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		model.addAttribute("roleId", roleId);
		Role role = roleServiceImpl.selectById(roleId);
		model.addAttribute("roleName", role.getRoleName());
		
		return "sys/role/grantApp";
	}
	
	@ResponseBody
	@RequestMapping(value = "/roleAppTree")
	public List<ZTreeModel> roleAppTree(
			@RequestParam(value = "roleId", required = true) String roleId,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws IOException {
		EntityWrapper<App> wrapper = new EntityWrapper<App>();
		wrapper.orderBy("appOrder");
		List<App> sysAppList = appServiceImpl.selectList(wrapper);
		List<ZTreeModel> treeList = new ArrayList<ZTreeModel>();
		for (int i = 0; i < sysAppList.size(); i++) {
			App app = sysAppList.get(i);
			if ("-1".equals(app.getAppID()) || "-1".equals(app.getAppPID())) {
				ZTreeModel atm = new ZTreeModel(app.getAppID(),
						app.getAppPID(), app.getAppName(), true,
						app.getAppIcon());
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/application/application_side_boxes.png");
				atm.setChecked(roleServiceImpl.setIfSetted(app.getAppID(), roleId));
				
				treeList.add(atm);
			} else {
				String appName = app.getAppName();
				ZTreeModel atm = new ZTreeModel(app.getAppID(),
						app.getAppPID(), appName, true, app.getAppIcon());
				atm.setIcon(request.getContextPath()
						+ "/static/zTree_v3/css/ext_icons/application/application_view_list.png");
				atm.setChecked(roleServiceImpl.setIfSetted(app.getAppID(), roleId));
				treeList.add(atm);
			}

		}
		return treeList;
	}
	
	@RequestMapping(value = "/grantRoleByUser")
	public String grantRoleByUser(@RequestParam(value = "userId", required = true) String userId,
			@RequestParam(value = "page", defaultValue = "1", required = true) int page,// 页号
			@RequestParam(value = "rows", defaultValue = "" + _ROWS_PER_PAGE, required = true) int rows,// 每页显示的记录条数
			@RequestParam(value = "roleName", defaultValue = "", required = false) String roleName,
			HttpServletRequest request, HttpServletResponse response, ModelMap model){
		Page<RoleVo> dataPage = new Page<RoleVo>();		
		dataPage.setCurrent(page);
		dataPage.setSize(rows);
		dataPage.setOrderByField("roleOrder");
		Map<String, Object> params = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(roleName)) {
			params.put("roleName", roleName);
		}
		params.put("userID", userId);
		List<RoleVo> roleVos = roleServiceImpl.selectRoleListPage(dataPage, params);
		dataPage.setRecords(roleVos);
		User user = userServiceImpl.selectById(userId);
		model.addAttribute("data", dataPage);
		model.addAttribute("userId", userId);
		model.addAttribute("roleName", roleName);
		model.addAttribute("userName", user.getUserName());
		model.addAttribute("userLoginName", user.getUserLoginName());
		return "sys/role/grantRoleByUser";
	}
	
	
	
	
}
